#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

vector<vector<int>> fourSum(vector<int>& nums, int target) {

    sort(nums.begin(), nums.end());
    size_t flag2 = 0;
    vector<vector<int>> v;
    while ((flag2 <= nums.size() - 4) && (nums.size() >= 4)) 
    {
        int flag1 = flag2 + 1;
        int a = target - nums[flag2];
        while ((flag1 <= nums.size() - 3)) {
            int left = flag1 + 1;
            int right = nums.size() - 1;
            while (left < right /* && nums[flag1] <= a*/) {
                if (nums[left] + nums[right] + nums[flag1] == a) {

                    v.push_back({ nums[flag2],nums[flag1], nums[left], nums[right]
                                  });
                    left++;
                    right--;
                    while ((nums[left] == nums[left - 1]) && (left < right))
                        left++;
                    while ((nums[right] == nums[right + 1]) &&
                        (left < right))
                        right--;
                }
                else if (nums[left] + nums[right] + nums[flag1] < a)
                    left++;
                else
                    right--;
            }
            flag1++;
            while (nums[flag1] == nums[flag1 - 1] &&
                (flag1 <= nums.size() - 3))
                flag1++;
        }
        flag2++;
        while (nums[flag2] == nums[flag2 - 1] && (flag2 <= nums.size() - 4))
            flag2++;
    }

    return v;
}

int main()
{
    vector<int>v1{ -1,0,-5,-2,-2,-4,0,1,-2 };

    vector<int>& v2 = v1;
    vector< vector<int>>v3=fourSum(v2, -9);
    for (const auto& innerVector : v3) {
        for (int num : innerVector) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
